<template>
    <div>
        <div class="n-layout-page-header">
            <n-card :bordered="false" title="分组管理">
                <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
                    <template #statusSlot="{ model, field }">
                        <n-input v-model:value="model[field]" />
                    </template>
                </BasicForm>
            </n-card>
        </div>
        <n-card :bordered="false" class="mt-4 proCard">
            <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
                :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" id="moss-basicTable" :bordered="false">
                <template #tableTitle>
                    <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        添加流程分组
                    </n-button>
                </template>
                <template #action>
                    <TableAction />
                </template>
            </BasicTable>
        </n-card>

        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle">
            <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
                <n-form-item label="分组名称" path="groupName">
                    <n-input maxlength="64" show-count placeholder="请输入分组名称" v-model:value="fromValues.groupName" />
                </n-form-item>
            </n-form>
            <div style="justify-content: end;display: flex;">
                <n-space>
                    <n-button ghost icon-placement="left" @click="handleCloseModel">
                        取消
                    </n-button>
                    <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
                </n-space>
            </div>
        </n-modal>

    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, unref } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { page, save, update, remove } from '@/api/flow/flowGroup';
import { columns } from './columns';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const actionRef = ref();
const showModal = ref(false);
const formBtnLoading = ref(false);
const editTitle = ref('');
const isAdd = ref(true);
const formRef: any = ref(null);
const dialog = useDialog();
const defaultValueRef = () => ({
    id: null,
    /**分组名称*/
    groupName: '',
});
let fromValues = reactive(defaultValueRef());
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
    /**查询参数*/
    {
        field: 'groupName',
        component: 'NInput',
        label: '分组名称',
        componentProps: {
            placeholder: '请输入分组名称',
        },
    },
];
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 120,
    schemas,
});
const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
        return h(TableAction as any, {
            style: 'text',
            actions: createActions(record),
        });
    },
});

function createActions(record) {
    return [
        {
            label: '删除',
            type: 'error',
            // 配置 color 会覆盖 type
            color: 'red',
            icon: DeleteOutlined,
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            //auth: ['basic_list'],
        },
        {
            label: '编辑',
            type: 'primary',
            icon: EditOutlined,
            onClick: handleEdit.bind(null, record, false),
            ifShow: () => {
                return true;
            },
            //auth: ['basic_list'],
        },
    ];
}
const rules: FormRules = {
    groupName: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入分组名称',
    },
};
const loadDataTable = async (res: any) => {
    return await page({ ...getFieldsValue(), ...res });
};

function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
}

function reloadTable() {
    actionRef.value.reload();
}
/**
 * 查询
 */
function handleSubmit() {
    reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
    reloadTable();
}
function resetFrom() {
    fromValues = Object.assign(unref(fromValues), defaultValueRef());
}
/**
 * 新增编辑提交数据
 * @param e
 */
function confirmForm(e: any) {
    e.preventDefault();
    formRef.value.validate(async (errors) => {
        if (!errors) {
            formBtnLoading.value = true;
            const data = isAdd.value ? await save(fromValues) : await update(fromValues);
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.mesg + '-' + resultMsg);
                formBtnLoading.value = false;
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.mesg);
                showModal.value = false;
                formBtnLoading.value = false;
                resetFrom();
                reloadTable();
            }
        } else {
            message.error('请填写完整信息');
        }
    });
}
/**
 * 新增编辑model
 * @param record
 * @param addStatus
 */
async function handleEdit(record: Recordable, addStatus: boolean) {
    showModal.value = true;
    isAdd.value = addStatus;
    if (addStatus) {
        editTitle.value = `新增模板`;
    } else {
        editTitle.value = "编辑";
        fromValues = Object.assign(fromValues, record);
    }
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
    resetFrom();
    showModal.value = false;
}
/**
 * 删除确认
 * @param record
 */
function handleDelete(record: Recordable) {
    dialog.warning({
        title: '警告',
        content: `确定删除吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const data = await remove({ id: record.id });
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.mesg + '-' + resultMsg);
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.mesg);
                reloadTable();
            }
        },
    })
}
</script>

<style lang="less" scoped></style>